<template>
  <template v-if="images.length">
    <div
      class="container relative"
      ref="container"
      :style="`--width: ${width}px; --height: ${images[0].height}px`"
    >
      <div class="swiper-wrapper">
        <div
          v-for="image in images"
          class="swiper-item"
          :style="`transform: translateX(${image.offset}px)`"
        >
          <img
            :src="image.url"
            :style="`width: ${image.width}px; height: ${image.height}px;`"
            draggable="false"
          />
        </div>
      </div>
    </div>
  </template>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import a1 from "./images/1.jpeg";
import a2 from "./images/2.jpeg";
import a3 from "./images/3.jpeg";
import a4 from "./images/4.jpeg";
import a5 from "./images/5.jpeg";

// 原始图片数据
type Image = {
  url: string;
  w: number;
  h: number;
};

// 扩展图片信息
type SlideImage = Image & {
  width: number; // 显示宽度
  height: number; // 显示高度
  offset: number;
};

type Size = {
  width: number;
  height: number;
};

const container = ref(null);

// 滑动时, 切换边界
const images = ref<Image[]>([]);
// 屏幕窗口宽度
const width = Math.min(480, window.innerWidth - 48);
// 当前索引
const selected = ref(0);

// 准备数据以及初始化
function load(url: string): Promise<Image> {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = function () {
      const w = image.naturalWidth;
      const h = image.naturalHeight;
      resolve({ w, h, url });
    };
    image.src = url;
  });
}

async function initImageList(images: string[]) {
  return Promise.all(images.map((url) => load(url)));
}

initImageList([a1, a1, a2, a3, a4, a5]).then((res) => {
  images.value = res;
});
</script>

<style scoped>
.container {
  margin: 16px auto 32px;
  touch-action: initial;
  cursor: grab;
}

.swiper-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: content-box;
  border-top: 10px solid #000;
  border-bottom: 10px solid #000;
  overflow: hidden;
}
.swiper-item {
  position: absolute;
  transition: all 0.05s;
}
.swiper-item img {
  display: block;
  max-width: initial;
}
</style>

<style>
body {
  overflow: hidden;
}
</style>
